import { Application, Session } from "mydog";
import { DEF } from "../../../app/definition/consts";
import { database_msg } from "../../../config/proto/database";

export default class Handler {
  private app: Application;
  constructor(app: Application) {
    this.app = app;
  }

  //-------------------------------------------------------------------------------
  //                              远程数据库操作
  //-------------------------------------------------------------------------------

  public async getUser(msg: database_msg.c2s_getUser, session: Session, next: Function) {
    const username = msg.username;

    const res: database_msg.s2c_getUser = new database_msg.s2c_getUser();

    const user = await this.app.rpcAwait(DEF.SEVER.ID.DATABASE).database.main.getUserByUsername(username);
    if (!!user) {

      res.code = DEF.SYSTEM.RETURN_CODE.SUCCESS;
      res.user = { id: user.id, username: user.username, nickname: user.nickname }
      next(res);
      return res;
    }
  }

  public async rename(msg: database_msg.c2s_rename, session: Session, next: Function) {
    const uid = msg.uid;
    const nickname = msg.nickname;

    const res: database_msg.s2c_rename = new database_msg.s2c_rename();

    const isOk = await this.app.rpcAwait(DEF.SEVER.ID.DATABASE).database.main.rename(uid, nickname);
    if (isOk) {
      res.code = DEF.SYSTEM.RETURN_CODE.SUCCESS;
      next(res);
      return;
    }
    res.code = DEF.SYSTEM.RETURN_CODE.SUCCESS;
    next(res);
  }

  public async getDoudizhuInfo(msg: database_msg.c2s_getDoudizhuInfo, session: Session, next: Function) {
    const uid = msg.uid;

    const res: database_msg.s2c_getDoudizhuInfo = new database_msg.s2c_getDoudizhuInfo();

    const doudizhuInfo = await this.app.rpcAwait(DEF.SEVER.ID.DATABASE).database.main.getDoudizhuInfo(uid);
    if (!!doudizhuInfo) {
      res.code = DEF.SYSTEM.RETURN_CODE.SUCCESS;
      res.info = { win: doudizhuInfo.win, lose: doudizhuInfo.lose, escape: doudizhuInfo.escape, gold: doudizhuInfo.gold };
      next(res);
      return;
    }
    res.code = DEF.SYSTEM.RETURN_CODE.SUCCESS;
    next(res);
  }
}
